import React, { useState } from 'react'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { Save, Eye, EyeOff, AlertTriangle, CheckCircle } from 'lucide-react'
import toast from 'react-hot-toast'
import { configApi } from '../services/api'

const ConfigPanel = () => {
  const [showPasswords, setShowPasswords] = useState({})
  const [formData, setFormData] = useState({})
  const queryClient = useQueryClient()

  // 获取当前配置
  const { data: config, isLoading } = useQuery({
    queryKey: ['config'],
    queryFn: () => configApi.getConfig().then(res => res.data),
    onSuccess: (data) => {
      setFormData(data)
    }
  })

  // 更新配置
  const updateConfigMutation = useMutation({
    mutationFn: configApi.updateConfig,
    onSuccess: (response) => {
      queryClient.invalidateQueries(['config'])
      toast.success('配置已更新')
      console.log('Update response:', response.data)
    },
    onError: (error) => {
      toast.error(`更新失败: ${error.response?.data?.detail || error.message}`)
    }
  })

  const handleInputChange = (field, value) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const togglePasswordVisibility = (field) => {
    setShowPasswords(prev => ({
      ...prev,
      [field]: !prev[field]
    }))
  }

  const handleSave = async () => {
    try {
      await updateConfigMutation.mutateAsync(formData)
    } catch (error) {
      console.error('Save failed:', error)
    }
  }

  if (isLoading) {
    return (
      <div className="p-6 h-full flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600 mx-auto"></div>
          <p className="text-sm text-gray-500 mt-2">加载配置中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="h-full overflow-y-auto">
      <div className="p-6">
        <div className="max-w-2xl">
          <div className="mb-6">
            <h2 className="text-xl font-semibold text-gray-900">系统配置</h2>
            <p className="text-sm text-gray-500 mt-1">
              配置API密钥和系统参数
            </p>
          </div>

          {/* 警告提示 */}
          <div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 mb-6">
            <div className="flex items-start">
              <AlertTriangle className="w-5 h-5 text-yellow-600 mt-0.5 mr-3" />
              <div>
                <h3 className="text-sm font-medium text-yellow-800">安全提醒</h3>
                <p className="text-sm text-yellow-700 mt-1">
                  API密钥仅用于当前会话的运行时配置，不会永久保存到文件中。
                  生产环境建议使用环境变量配置。
                </p>
              </div>
            </div>
          </div>

          <div className="space-y-6">
            {/* Midscene 配置 */}
            <div className="card">
              <div className="card-header">
                <h3 className="text-lg font-medium">Midscene 配置</h3>
                <p className="text-sm text-gray-500">控制AI Agent执行时使用的模型和API</p>
              </div>
              <div className="card-content space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    模型名称
                  </label>
                  <input
                    type="text"
                    className="input w-full"
                    placeholder="例如: google/gemini-2.5-flash-preview"
                    value={formData.MIDSCENE_MODEL_NAME || ''}
                    onChange={(e) => handleInputChange('MIDSCENE_MODEL_NAME', e.target.value)}
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    当前: {config?.MIDSCENE_MODEL_NAME || '未设置'}
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    OpenAI API 密钥
                  </label>
                  <div className="relative">
                    <input
                      type={showPasswords.OPENAI_API_KEY ? 'text' : 'password'}
                      className="input w-full pr-10"
                      placeholder="留空使用系统环境变量"
                      value={formData.OPENAI_API_KEY || ''}
                      onChange={(e) => handleInputChange('OPENAI_API_KEY', e.target.value)}
                    />
                    <button
                      type="button"
                      className="absolute inset-y-0 right-0 pr-3 flex items-center"
                      onClick={() => togglePasswordVisibility('OPENAI_API_KEY')}
                    >
                      {showPasswords.OPENAI_API_KEY ? (
                        <EyeOff className="h-4 w-4 text-gray-400" />
                      ) : (
                        <Eye className="h-4 w-4 text-gray-400" />
                      )}
                    </button>
                  </div>
                  <div className="flex items-center mt-1">
                    {config?.OPENAI_API_KEY_SET ? (
                      <div className="flex items-center text-xs text-green-600">
                        <CheckCircle className="w-3 h-3 mr-1" />
                        已设置
                      </div>
                    ) : (
                      <div className="text-xs text-gray-500">未设置</div>
                    )}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Base URL (可选)
                  </label>
                  <input
                    type="text"
                    className="input w-full"
                    placeholder="留空使用默认 OpenAI 地址"
                    value={formData.OPENAI_BASE_URL || ''}
                    onChange={(e) => handleInputChange('OPENAI_BASE_URL', e.target.value)}
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    当前: {config?.OPENAI_BASE_URL || '默认'}
                  </p>
                </div>
              </div>
            </div>

            {/* Planner 配置 */}
            <div className="card">
              <div className="card-header">
                <h3 className="text-lg font-medium">Planner 配置</h3>
                <p className="text-sm text-gray-500">控制用于规划步骤的LLM模型</p>
              </div>
              <div className="card-content space-y-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    模型名称
                  </label>
                  <input
                    type="text"
                    className="input w-full"
                    placeholder="例如: openai/gpt-4o"
                    value={formData.planner_llm_model || ''}
                    onChange={(e) => handleInputChange('planner_llm_model', e.target.value)}
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    当前: {config?.planner_llm_model || '未设置'}
                  </p>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Planner API 密钥
                  </label>
                  <div className="relative">
                    <input
                      type={showPasswords.PLANNER_OPENAI_API_KEY ? 'text' : 'password'}
                      className="input w-full pr-10"
                      placeholder="留空使用 Midscene 密钥"
                      value={formData.PLANNER_OPENAI_API_KEY || ''}
                      onChange={(e) => handleInputChange('PLANNER_OPENAI_API_KEY', e.target.value)}
                    />
                    <button
                      type="button"
                      className="absolute inset-y-0 right-0 pr-3 flex items-center"
                      onClick={() => togglePasswordVisibility('PLANNER_OPENAI_API_KEY')}
                    >
                      {showPasswords.PLANNER_OPENAI_API_KEY ? (
                        <EyeOff className="h-4 w-4 text-gray-400" />
                      ) : (
                        <Eye className="h-4 w-4 text-gray-400" />
                      )}
                    </button>
                  </div>
                  <div className="flex items-center mt-1">
                    {config?.PLANNER_OPENAI_API_KEY_SET ? (
                      <div className="flex items-center text-xs text-green-600">
                        <CheckCircle className="w-3 h-3 mr-1" />
                        已设置
                      </div>
                    ) : (
                      <div className="text-xs text-gray-500">未设置</div>
                    )}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    Planner Base URL (可选)
                  </label>
                  <input
                    type="text"
                    className="input w-full"
                    placeholder="留空使用默认地址"
                    value={formData.PLANNER_OPENAI_BASE_URL || ''}
                    onChange={(e) => handleInputChange('PLANNER_OPENAI_BASE_URL', e.target.value)}
                  />
                  <p className="text-xs text-gray-500 mt-1">
                    当前: {config?.PLANNER_OPENAI_BASE_URL || '默认'}
                  </p>
                </div>
              </div>
            </div>

            {/* 其他设置 */}
            <div className="card">
              <div className="card-header">
                <h3 className="text-lg font-medium">其他设置</h3>
              </div>
              <div className="card-content">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    日志级别
                  </label>
                  <select
                    className="input w-full"
                    value={formData.logging_level || 'INFO'}
                    onChange={(e) => handleInputChange('logging_level', e.target.value)}
                  >
                    <option value="DEBUG">调试 (DEBUG)</option>
                    <option value="INFO">信息 (INFO)</option>
                    <option value="WARNING">警告 (WARNING)</option>
                    <option value="ERROR">错误 (ERROR)</option>
                  </select>
                  <p className="text-xs text-gray-500 mt-1">
                    当前: {config?.logging_level || 'INFO'}
                  </p>
                </div>
              </div>
            </div>
          </div>

          {/* 保存按钮 */}
          <div className="mt-8 flex justify-end">
            <button
              onClick={handleSave}
              disabled={updateConfigMutation.isLoading}
              className="btn-primary disabled:opacity-50"
            >
              {updateConfigMutation.isLoading ? (
                <>
                  <div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
                  保存中...
                </>
              ) : (
                <>
                  <Save className="w-4 h-4 mr-2" />
                  保存配置
                </>
              )}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}

export default ConfigPanel